import 'package:flutter/material.dart';
import '../utils/http_client.dart';
import 'tasks/ongoing_tasks_screen.dart';
import 'tasks/completed_tasks_screen.dart';
import 'profile/profile_screen.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';


class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _currentIndex = 0;

  final List<Widget> _screens = [
    const OngoingTasksScreen(),
    const CompletedTasksScreen(),
    const ProfileScreen(),
  ];

  @override
  void initState() {
    super.initState();
    // 在主页面加载后检查更新
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkUpdate();
    });
  }

  Future<void> _checkUpdate() async {
    try {
      // 获取当前版本
      final packageInfo = await PackageInfo.fromPlatform();
      final localVersion = packageInfo.version;

      // 请求服务器版本
      final response = await HttpClient.dio.post('/follower/checkUpdate');

      if (response.data['code'] == 0) {
        final serverData = response.data;
        final serverVersion = serverData['data']['version'];
        final downloadUrl = serverData['data']['url'];
        final message = serverData['msg'];
        final force = serverData['data']['force'] == true;
        print("$localVersion,$serverVersion");
        // 比较版本号
        if (_compareVersion(localVersion, serverVersion) < 0 && mounted) {
          showDialog(
            context: context,
            barrierDismissible: !force,
            builder: (context) => WillPopScope(
              onWillPop: () async => !force,
              child: AlertDialog(
                title: const Row(
                  children: [
                    Icon(Icons.system_update, color: Colors.orange),
                    SizedBox(width: 8),
                    Text('发现新版本'),
                  ],
                ),
                content: Text(message),
                actions: [
                  if (!force)
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: const Text('稍后再说'),
                    ),
                  ElevatedButton(
                    onPressed: () async {
                      final uri = Uri.parse(downloadUrl);
                      if (await canLaunchUrl(uri)) {
                        await launchUrl(
                          uri,
                          mode: LaunchMode.externalApplication,
                        );
                      }
                      if (!force && context.mounted) {
                        Navigator.pop(context);
                      }
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.orange,
                    ),
                    child: const Text('立即更新'),
                  ),
                ],
              ),
            ),
          );
        }
      }
    } catch (e) {
      debugPrint('Version check failed: $e');
    }
  }

  int _compareVersion(String v1, String v2) {
    final v1Parts = v1.split('.').map(int.parse).toList();
    final v2Parts = v2.split('.').map(int.parse).toList();

    for (var i = 0; i < v1Parts.length || i < v2Parts.length; i++) {
      final v1Part = i < v1Parts.length ? v1Parts[i] : 0;
      final v2Part = i < v2Parts.length ? v2Parts[i] : 0;
      if (v1Part > v2Part) return 1;
      if (v1Part < v2Part) return -1;
    }
    return 0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _screens[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.assignment),
            label: '进行中',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.assignment_turned_in),
            label: '已完成',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: '我的',
          ),
        ],
      ),
    );
  }
} 